//
//  XMLParser.m
//  XmlDemo
//
//  Created by ellenpage on 12-11-27.
//  Copyright (c) 2012年 ellenpage. All rights reserved.
//

#import "XMLParser.h"

@interface XMLParser ()<NSXMLParserDelegate>

@end

@implementation XMLParser

static XMLParser *sharedXml = nil;

+ (XMLParser *)sharedInstance
{
    @synchronized(self)
    {
        if (sharedXml == nil)
        {
            sharedXml = [[self alloc] init];
        }
    }
    return  sharedXml;
}

- (void)startParser:(NSData *)data
{
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; //设置XML数据
    
    [parser setShouldProcessNamespaces:NO];
    [parser setShouldReportNamespacePrefixes:NO];
    [parser setShouldResolveExternalEntities:NO];
    
    [parser setDelegate:self];
    [parser parse];
}

//遍历节点
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    _elenmentStr = elementName;
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(startParser:)])
    {
        [self.delegate startParser:elementName];
    }
}

//发现节点
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(findCharacters:elenment:)])
    {
        [self.delegate findCharacters:string elenment:_elenmentStr];
    }
}

//结束遍历
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(endParser:)])
    {
        [self.delegate endParser:elementName];
    }
}

@end
